﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Business.Campaigns;
using iOak.Domain.Campaigns;
using iOak.Common.Untity;
using System.Transactions;
using iOak.Business.Resumes;
using iOak.Domain.Resumes;

namespace iOak.Web.Administration
{
    public partial class ApplicationCheck : BasePage
    {
        private WorkAssistant _workassistant = new WorkAssistant();

        private ApplicationCandidate ApplicationCandidateItem
        {
            get
            {
                ApplicationCandidate applicationCandidateItem = null;
                if (this.Session["ApplicationCheck_ApplicationCandidate"] != null)
                {
                    applicationCandidateItem = this.Session["ApplicationCheck_ApplicationCandidate"] as ApplicationCandidate;
                }
                return applicationCandidateItem;
            }
            set
            {
                this.Session["ApplicationCheck_ApplicationCandidate"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!String.IsNullOrWhiteSpace(this.Request.QueryString["applicationId"]) &&
                    !String.IsNullOrWhiteSpace(this.Request.QueryString["applicationCandidateId"]))
                {
                    Guid applicationId = Guid.Parse(this.Request.QueryString["applicationId"]);
                    Guid applicationCandidateId = Guid.Parse(this.Request.QueryString["applicationCandidateId"]);
                    IniData(applicationId, applicationCandidateId);
                    SetTemplate(true);
                    //如果是查看模式
                    ViewState["viewMode"] = "0";
                    if (!String.IsNullOrWhiteSpace(this.Request.QueryString["viewMode"]) && this.Request.QueryString["viewMode"].Equals("1")) 
                    {
                        ViewState["viewMode"] = "1";
                        btnOk.Visible = false;
                        btnOk2.Visible = false;
                        btnCancel.Text = "返回";
                        btnCancel2.Text = btnCancel.Text;
                        //btnContinue.Text = "查看下一个";
                        //btnContinue2.Text = btnContinue.Text;
                        btnContinue.Visible = false;
                        btnContinue2.Visible = false;
                        phCheck.Visible = false;
                        btnEdit.Visible = false;
                    }
                }
            }
            else
            {
                if (hidBindTemplate.Value.Equals("1"))
                {
                    SetTemplate(false);
                }
                else if (hidBindTemplate.Value.Equals("2"))
                {
                    SetTemplate(true);
                }
                else
                {
                    hidBindTemplate.Value = "1";
                }
            }
        }

        private void IniData(Guid applicationId, Guid applicationCandidateId)
        {
            btnCancel.OnClientClick = "btnCancelClick('" + applicationId.ToString() + "');return false;";
            btnCancel2.OnClientClick = btnCancel.OnClientClick;
            ApplicationCandidateService applicationCandidateService = new ApplicationCandidateService();
            List<ApplicationCandidate> applicationCandidateList = applicationCandidateService.GetListByApplicationId(applicationId);
            ApplicationCandidateItem = applicationCandidateList.FirstOrDefault(item => item.ApplicationCandidateId.Equals(applicationCandidateId));
            this.ViewState["ResumeId"] = ApplicationCandidateItem.ResumeId;
            if (ApplicationCandidateItem != null)
            {
                //获取下一个未完成的ApplicationCandidate
                ApplicationCandidate nextApplicationCandidate = applicationCandidateList.FirstOrDefault(item => !item.ApplicationCandidateId.Equals(applicationCandidateId) &&
                                                                                                        item.Passed == null);
                if (nextApplicationCandidate != null)
                {
                    this.ViewState["NextApplicationCandidateId"] = nextApplicationCandidate.ApplicationCandidateId.ToString();
                }
                else
                {
                    //若果存在其他未完成的ApplicationCandidate
                    btnContinue.Visible = false;
                    btnContinue2.Visible = false;
                }
                if (ApplicationCandidateItem.Passed.HasValue)
                {
                    if (ApplicationCandidateItem.Passed.Value)
                    {
                        rblPassed.SelectedIndex = 0;
                    }
                    else
                    {
                        rblPassed.SelectedIndex = 1;
                    }
                }
                txtNotes.Text = ApplicationCandidateItem.Notes;
                txtScore.Text = ApplicationCandidateItem.Score.ToString();
            }
        }

        private void SetTemplate(bool readMode)
        {
            ApplicationService applicationService = new ApplicationService();
            ApplicationBase application = applicationService.Retrieve(ApplicationCandidateItem.ApplicationId);
            CampaignService campaignService = new CampaignService();
            Campaign campaign = campaignService.Retrieve(application.CampaignId);
            PolicyService policyService = new PolicyService();
            Policy policy = policyService.Retrieve(campaign.PolicyId);
            lblSubject.Text = policy.Subject;
            lblDescription.Text = policy.Description;
            if (policy != null)
            {
                // 加载用户控件
                ResumeTemplateService resumeTemplateService = new ResumeTemplateService();
                ResumeTemplate resumeTemplate = resumeTemplateService.Retrieve(policy.ResumeTemplateId);

                if (readMode)
                {
                    divTemple.Visible = true;
                    divTempleEdit.Visible = false;
                    BaseUserControl detialControl = LoadControl(resumeTemplate.ViewTemplatePath) as BaseUserControl;
                    detialControl = LoadControl(resumeTemplate.ViewTemplatePath) as BaseUserControl;
                    divTemple.Controls.Add(detialControl);
                    detialControl.BindData(policy.ResumeTemplateId, ApplicationCandidateItem.ResumeId);
                }
                else
                {
                    divTemple.Visible = false;
                    divTempleEdit.Visible = true;
                    BaseUserControl detialControlEdit = LoadControl(resumeTemplate.TemplatePath) as BaseUserControl;
                    detialControlEdit = LoadControl(resumeTemplate.TemplatePath) as BaseUserControl;
                    divTempleEdit.Controls.Add(detialControlEdit);
                    detialControlEdit.BindData(policy.ResumeTemplateId, ApplicationCandidateItem.ResumeId.ToString(), ApplicationCandidateItem.ApplicationId, ApplicationCandidateItem.ApplicationCandidateId.ToString(), true);
                }
            }
        }

        private void SaveData()
        {
            ApplicationCandidateService applicationCandidateService = new ApplicationCandidateService();
            Guid applicationCandidateId = Guid.Parse(this.Request.QueryString["applicationCandidateId"]);
            ApplicationCandidate applicationCandidate = applicationCandidateService.Retrieve(applicationCandidateId);
            if (rblPassed.SelectedIndex != -1)
            {
                applicationCandidate.Passed = rblPassed.SelectedIndex == 0;
            }
            applicationCandidate.Notes = txtNotes.Text;
            applicationCandidate.CheckerOn = DateTime.Now;
            if (!String.IsNullOrWhiteSpace(txtScore.Text))
            {
                applicationCandidate.Score = int.Parse(txtScore.Text);
            }
            using (TransactionScope ts = new TransactionScope())
            {
                applicationCandidateService.Update(applicationCandidate);
                Guid applicationId = Guid.Parse(this.Request.QueryString["applicationId"]);
                ApplicationService applicationService = new ApplicationService();
                ApplicationBase application = applicationService.Retrieve(applicationId);
                //如果continue按钮不显示，说明不存在其他未审核的候选人
                if (!btnContinue.Visible)
                {
                    //改变申请书状态
                    //if (application.Status != (int)ApplicationStatus.Checked)
                    //如果当前申请书中的所有候选人都已经通过，则改变状态
                    if(applicationCandidateService.AllPassed(applicationId))
                    {
                        application.Status = (int)ApplicationStatus.Checked;
                        applicationService.Update(application);
                    }
                }
                //else
                //{
                //    if (application.Status != (int)ApplicationStatus.Checking)
                //    {
                //        application.Status = (int)ApplicationStatus.Checking;
                //        applicationService.Update(application);
                //    }
                //}
                ts.Complete();
            }
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            SaveData();
            ClientScript.RegisterStartupScript(typeof(Page), "back", "btnCancelClick('" + this.Request.QueryString["applicationId"] + "');", true);
        }

        protected void btnContinue_Click(object sender, EventArgs e)
        {
            SaveData();
            string url = String.Format("ApplicationCheck.aspx?applicationId={0}&applicationCandidateId={1}",
                                                  this.Request.QueryString["applicationId"],
                                                  this.ViewState["NextApplicationCandidateId"].ToString());
            this.Response.Redirect(url + "&viewMode=" + ViewState["viewMode"].ToString());
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            SetTemplate(false);
        }
    }
}